package io.plus.client;

import io.plus.common.io;
import io.plus.common.packet.auth.LoginRequestMessage;
import io.plus.common.packet.message.ChatMessage;
import io.plus.common.packet.metadata.Command;
import io.plus.common.protocol.Packet;
import io.plus.engine.client.*;
import io.plus.engine.pulse.Node;
import io.plus.server.Status;

public class ClientStarter {
    /**
     * 服务器节点
     */
    public static Node node = new Node("127.0.0.1", 1356);
    /**
     * handler, 包括编码、解码、消息处理
     */
    public static ClientHandler clientHandler = new ClientHandlerImpl();


    public static Client client = null;
    public static ClientAsynchronousSocketChannelContext clientChannelContext = null;
    /**
     * 断链后自动连接的，不想自动连接请设为null
     */
    private static ReConnectConfiguration reConnectConfiguration = new ReConnectConfiguration(5000L);
    /**
     * 一组连接共用的上下文对象
     */
    public static ClientConfiguration clientConfiguration = new ClientConfiguration(clientHandler, reConnectConfiguration);

    /**
     * 启动程序入口
     */
    public static void main(String[] args) throws Exception {

        clientConfiguration.setHeartbeatTimeout(0);
        client = new Client(clientConfiguration);
        clientChannelContext = client.connect(node);
        // 连上后，发条消息玩玩
        send();
    }

    private static void send() {
        LoginRequestMessage loginRequestMessage = new LoginRequestMessage("hello_client", "123");
        Packet packet = new Packet(Command.login_request, Status.ok, loginRequestMessage.toByte());
        // 先登录;
        io.send(clientChannelContext, packet);
        ChatMessage chatMessage = ChatMessage.newBuilder().setFrom("hello_client").setTo("admin").setMsgType(0).setChatType(1)
                .setGroup_id("100").setContent("Socket普通客户端消息测试!").build();
        Packet chatPacket = new Packet(Command.chat_request, Status.ok, chatMessage.getFrom().getBytes());
        io.send(clientChannelContext, chatPacket);
    }
}
